package com.rx.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rx.entity.Role;
import com.rx.service.RoleServiceI;
import com.rx.service.RoleServiceImpl;

@WebServlet("/RoleServlet")
public class RoleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RoleServiceI<Role> rsi = new RoleServiceImpl();
		String flag = request.getParameter("flag");
		if ("edit".equals(flag)) {
			// 进记录修改
			Integer id = Integer.valueOf(request.getParameter("id"));
			try {
				List<Role> list = rsi.GetIdRole(id);
				if (list.size() > 0) {
					Role role = list.get(0);
					request.setAttribute("role", role);
					//
					request.getRequestDispatcher("/admin/addRole.jsp").forward(request, response);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("del".equals(flag)) {
			//删除操作
			try {
				if(rsi.remove(Integer.valueOf(request.getParameter("id")))){
					response.sendRedirect("/RoleServlet");
				}else {
					response.getWriter().write("修改失败");
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			try {
				List<Role> list = rsi.getAll();
				request.setAttribute("list", list);
				request.getRequestDispatcher("/admin/role.jsp").forward(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设定编码
		request.setCharacterEncoding("UTF-8");
		String roleName = request.getParameter("roleName");
		String remark = request.getParameter("remark");

		RoleServiceI<Role> rsi = new RoleServiceImpl();

		String id = request.getParameter("id");
		if (null != id) {
			Role role = new Role();
			role.setId(Integer.valueOf(id));
			role.setRoleName(roleName);
			role.setRemark(remark);
			try {
				if (rsi.modify(role)) {
					response.sendRedirect("/RoleServlet");
				} else {
					response.getWriter().write("修改失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {
			Role role = new Role();
			role.setRoleName(roleName);
			role.setRemark(remark);
			try {
				if (rsi.add(role)) {
					response.sendRedirect("/RoleServlet");
				} else {
					response.getWriter().write("添加失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
